﻿Imports System.Data.OleDb
Imports ewinsync.ewindt
Public Class WinccHandler
    Implements IWinccHandler

    Private verrs As String
    Private Shared instance As WinccHandler
    Private wcc As WinccConfig
    Private cx As OleDbConnection
    Private wcx As OleDbConnection
    Private log As ActivityLogger
    Public Sub closeConnection() Implements IWinccHandler.closeConnection
        If (IsNothing(cx)) Then Return
        cx.Close()
    End Sub

    Public Property Errors As String Implements IWinccHandler.Errors
        Get
            Return verrs
        End Get
        Set(ByVal value As String)
            verrs = value
        End Set
    End Property

    Public Function getAlarmValue() As System.Data.DataTable Implements IWinccHandler.getAlarmValue
        Return Nothing
    End Function

    Public Function getSharedInstance() As IWinccHandler Implements IWinccHandler.getSharedInstance
        If (IsNothing(instance)) Then instance = New WinccHandler
        Return instance
    End Function
    Public Shared Function getInstance() As IWinccHandler
        If (IsNothing(instance)) Then instance = New WinccHandler
        Return instance
    End Function

    Public Function openConnection() As Boolean Implements IWinccHandler.openConnection
        If (IsNothing(cx)) Then
            cx = New OleDbConnection(WConfig.getConnectionString)
        End If
        If (cx.State = ConnectionState.Open) Then
            closeConnection()
        End If
        Try
            cx.Open()
        Catch ex As Exception
            Errors = "Error Opening connection to " + WConfig.Datasource + vbCrLf + ex.Message
            Return True 'just to bypass connection opening test
            'Return False
        End Try
        Return True
    End Function
    Private Function getConnection() As OleDbConnection
        If (IsNothing(cx)) Then openConnection()
        Return cx
    End Function
    Public Function testconnection() As Boolean Implements IWinccHandler.testconnection
        Dim ret As Boolean = openConnection()
        If (ret) Then closeConnection()
        Return ret
    End Function

    Public Property WConfig As WinccConfig Implements IWinccHandler.WConfig
        Get
            Return wcc
        End Get
        Set(ByVal value As WinccConfig)
            wcc = value
        End Set
    End Property

    Sub New()
        WConfig = New WinccConfig
        log = ActivityLogger.getInstance
    End Sub

    Public Function listTag() As ewindt.DtTagListDataTable Implements IWinccHandler.listTag
        Try
            Dim px As OleDbConnection = New OleDbConnection(WConfig.getTagConnectionString)
            px.Open()
            Dim cmd As OleDbCommand = New OleDbCommand("select * from Archives", px)
            Dim reader As OleDbDataReader = cmd.ExecuteReader()
            Dim ret As New ewindt.DtTagListDataTable
            While reader.Read
                Dim id = reader.Item(WinccConfig.TAGID)
                Dim value = reader.Item(WinccConfig.TAGNAME)
                Dim r = ret.NewDtTagListRow
                r.ValueID = id
                r.ValueName = value
                ret.AddDtTagListRow(r)
            End While
            ret.AcceptChanges()
            reader.Close()
            px.Close()
            Return ret
        Catch ex As Exception
            doLog("Error Occured [listTag]:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
        End Try
        Return Nothing
    End Function

    Public Function getTagValue(ByVal startdate As Date, ByVal enddate As Date, ByVal tag As System.Collections.ArrayList) As ewindt.DtProcessValueDataTable Implements IWinccHandler.getTagValue
        Try
            Dim px As OleDbConnection = getConnection()
            If (IsNothing(px)) Then Return Nothing
            Dim sql As String = "TAG:R,"
            Dim taglist As String = ""
            For Each i As WcTagValue In tag
                taglist = taglist + "'" + i.ValueName + "';"
            Next
            taglist = taglist.TrimEnd({";"c})
            sql = sql + taglist + "'," + convertDate(startdate) + "','" + convertDate(enddate) + "','TIMESTEP=5',261"
            doLog("Getting Tag Value SQl:" + sql, ActivityLoggerConf.LOGLEVEL_INFO)
            Dim cmd As OleDbCommand = New OleDbCommand(sql, px)
            Dim reader As OleDbDataReader = cmd.ExecuteReader()
            Dim ret As New ewindt.DtProcessValueDataTable
            While reader.Read
                Dim id = reader.Item(WinccConfig.PROCTAGID)
                Dim tsm = System.DateTime.Parse(reader.Item(WinccConfig.PROCTAGTIME).ToString).ToLocalTime
                Dim rval = reader.Item(WinccConfig.PROCTAGVAL)
                Dim r = ret.NewDtProcessValueRow
                r.ValueID = id
                r.RealValue = rval
                r.TimeStamp = tsm
                ret.AddDtProcessValueRow(r)
            End While
            ret.AcceptChanges()
            reader.Close()
            px.Close()
            doLog("Getting Tag Value SQl:" + sql + " done", ActivityLoggerConf.LOGLEVEL_INFO)
            Return ret
        Catch ex As Exception
            doLog("Error Occured [getTagValue]:" + ex.Message, ActivityLoggerConf.LOGLEVEL_ERROR)
        End Try
        Return Nothing
    End Function
    Private Function convertDate(ByVal dt As DateTime) As String
        Dim localDateTimeFrom As DateTime = System.DateTime.Parse(dt.ToString())
        Dim univDateTimeFrom As Date = localDateTimeFrom.ToUniversalTime()
        Dim tfrom As String = dt.Year.ToString() + "-" + String.Format("{0:MM}", univDateTimeFrom.Month.ToString()) + "-" + String.Format("{0:dd}", univDateTimeFrom.Day.ToString()) + " " + String.Format("{0:HH}", univDateTimeFrom.Hour.ToString()) + ":" + String.Format("{0:mm}", univDateTimeFrom.Minute.ToString()) + ":" + String.Format("{0:ss}", univDateTimeFrom.Second.ToString())
        Return tfrom
    End Function
    Public Function openWinCcConnection() As Boolean Implements IWinccHandler.openWinCcConnection
        Return True
    End Function
    Private Sub doLog(ByVal msg As String, ByVal sev As String)
        log.log(commons.MOD_WINCCHANDLER, msg, sev)
    End Sub

    Public Function getAlarmsField() As ewindt.DtTagListDataTable Implements IWinccHandler.getAlarmsField
        Dim ret As New ewindt.DtTagListDataTable
        setAlarmField(ret, "MsgNo", "Message number", MySql.Data.MySqlClient.MySqlDbType.Int32, 1)
        setAlarmField(ret, "State", "Alarm Log Status", MySql.Data.MySqlClient.MySqlDbType.Int32, 2)
        setAlarmField(ret, "DateTime", "Time stamp of the message", MySql.Data.MySqlClient.MySqlDbType.DateTime, 3)
        setAlarmField(ret, "Ms", "Time stamp of the message", MySql.Data.MySqlClient.MySqlDbType.Timestamp, 4)
        setAlarmField(ret, "Instance", "Instance Name of the Alarm Log", MySql.Data.MySqlClient.MySqlDbType.VarChar, 5)
        setAlarmField(ret, "Flags1", "Message number", MySql.Data.MySqlClient.MySqlDbType.Int32, 6)
        setAlarmField(ret, "PValueUsed", "Message number", MySql.Data.MySqlClient.MySqlDbType.Int32, 7)
        setAlarmField(ret, "Pvalue1toPValue10", "Message number", MySql.Data.MySqlClient.MySqlDbType.Double, 8)
        setAlarmField(ret, "Comment", "Comments", MySql.Data.MySqlClient.MySqlDbType.VarChar, 30)
        Return ret
    End Function
    Private Sub setAlarmField(ByRef dt As ewindt.DtTagListDataTable, ByVal fn As String, ByVal expla As String, ByVal type As MySql.Data.MySqlClient.MySqlDbType, ByVal valueid As Integer)
        Dim n As ewindt.DtTagListRow = dt.NewDtTagListRow
        n.ValueID = valueid
        Dim des As String = fn + "[" + expla + "," + type.ToString + "]"
        n.ValueName = des
        dt.AddDtTagListRow(n)
    End Sub
End Class
